﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace CoreLib.Extensions
{
    public static class IEnumerableExt
    {
        public static IEnumerable<Out> Map<In, Out>( this IEnumerable<In> target, Func<In, Out> mapper )
        {
            foreach( var item in target )
                yield return mapper( item );
        }

        public static IEnumerable<T> Collect<T>( this IEnumerable<T> target, Func<T, bool> predicate )
        {
            foreach( var item in target )
                if( predicate( item ) )
                    yield return item;
        }

        public static void ForEach<T>( this IEnumerable<T> target, Action<T> action )
        {
            foreach( var item in target )
                action( item );
        }

        public static IEnumerable<T> Filter<T>(this IEnumerable<T> target, Func<T, bool> predicate)
        {
            return Collect(target, predicate);
        }

        public static bool IsEmpty<T>( this IEnumerable<T> target )
        {
            return target.Count() < 1;
        }

        public static IEnumerable<T> RemoveNulls<T>(this IEnumerable<T> target) where T : class
        {
            return Collect(target, t => t != null);
        }

        public static void ForEach<T>( this IEnumerable target, Action<T> action )
        {
            foreach( var item in target )
                action( (T)item );
        }

        public static string Join(this IEnumerable<string> target, string separator)
        {
            return string.Join(separator, target.ToArray());
        }
    }
}
